package com.joolun.weixin.service.impl;

import com.alibaba.fastjson2.JSON;
import com.joolun.common.config.ScrmConfig;
import com.joolun.common.corp.TenantContext;
import com.joolun.system.domain.SysCorpConfig;
import com.joolun.system.service.impl.SysCorpConfigServiceImpl;
import com.joolun.weixin.config.WxCpConfiguration;
import com.joolun.weixin.service.IWxPortalService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author xuxh
 * @date 2022/2/15 9:26
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class WxPortalServiceImpl implements IWxPortalService {
    @Autowired
    private SysCorpConfigServiceImpl sysCorpConfigService;
    @Override
    public String handler(Integer agentId, String requestBody, String signature, String timestamp, String nonce) {
        log.info("\n接收微信请求：[signature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                signature, timestamp, nonce, requestBody);

        // 获取主体配置
        SysCorpConfig sysCorpConfig = sysCorpConfigService.getById(agentId);
        System.out.println("post主体配置" + sysCorpConfig);
        final WxCpService wxCpService = WxCpConfiguration.getAddressBookWxCpService(sysCorpConfig);
        WxCpXmlMessage inMessage = WxCpXmlMessage.fromEncryptedXml(requestBody, wxCpService.getWxCpConfigStorage(),
                timestamp, nonce, signature);
        log.debug("\n消息解密后内容为：\n{} ", JSON.toJSONString(inMessage));
        //返回
        WxCpXmlOutMessage outMessage = route(sysCorpConfig.getCorpId(), inMessage);
        if (outMessage == null) {
            return "";
        }
        String out = outMessage.toEncryptedXml(wxCpService.getWxCpConfigStorage());
        log.debug("\n组装回复信息：{}", out);
        return out;
    }

    public WxCpXmlOutMessage route(String corpId, WxCpXmlMessage message) {
        try {
            System.out.println("route -- corpId -- " + corpId);
            return WxCpConfiguration.getRouters().get(corpId).route(message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }
}
